<?php
declare (strict_types = 1);

namespace app\srapi\controller;
use hg\apidoc\annotation as Apidoc;
use app\common\controller\SrapiUserController;
use think\facade\Db;
/**
 * @Apidoc\Title("个人中心")
 * @Apidoc\Group("User")
 */
class User extends SrapiUserController
{
    /**
     * @Apidoc\Title("编辑信息")
     * @Apidoc\Method("POST")
     * @Apidoc\Tag("sr")
     * @Apidoc\Param("nickname", require=true, desc="昵称")
     * @Apidoc\Param("avatar", require=true, desc="头像")
     * @Apidoc\Returned("update_time", type="string", desc="update_time")
     * @Apidoc\Returned("user_id", type="int", desc="用户id")
     */
    public function userinfo(){
        $data = $this->request->post();
        $currentTime = time();
        $res = Db::name("user")
            ->where(['id'=>$this->userId])
            ->update([
                'nickname' => $this->emoji($data['nickname']),
                'avatar' => $data['avatar'],
                'update_time' => $currentTime
            ]);
        $res ? $this->success("更新成功!", ['user_id'=>$this->userId, 'update_time'=>$currentTime]) : $this->error("更新失败!",);
    }
    /**
     * @Apidoc\Title("详情")
     * @Apidoc\Method("GET")
     * @Apidoc\Tag("sr")
     * @Apidoc\Returned("nickname", type="string", desc="昵称")
     * @Apidoc\Returned("avatar", type="string", desc="头像")
     * @Apidoc\Returned("tel", type="string", desc="手机")
     */
    public function detail(){
        $info = Db::name("user")->where('id',$this->userId)->field('id,nickname,avatar,tel')->find();
        $this->success("",$info);
    }
    
    function emoji($text) {
        $text = iconv('UTF-8', 'GBK//IGNORE', $text);
        $text = iconv('GBK', 'UTF-8//IGNORE', $text);

        return $text;
    }

    /**
     * @Apidoc\Title("手机号授权")
     * @Apidoc\Method("POST")
     * @Apidoc\Tag("sr")
     * @Apidoc\Param("code", require=true, desc="e.detail.code")
     * @Apidoc\Returned("number", type="string", desc="手机号")
     */
    public function getPhone(){
        $data = $this->request->post();
        $this->validate($data,[
            'code' => 'require'
        ],[
            'code.require' => '缺少参数code!'
        ]);
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$access_token;
        $json = $this->http_request($url,json_encode(['code'=>$data['code']]));

        $res = json_decode($json, true);
        if(!empty($res['errcode'])){
            $this->error($res['errmsg']);
        }
        
        Db::name("user")
            ->where(['id'=>$this->userId])
            ->update([
                'tel'   => $res['phone_info']['purePhoneNumber']
            ]);
        $this->success('ok',[
            "number" => $res['phone_info']['purePhoneNumber']
        ]);
    }
}
